import React, { Component, PropTypes } from 'react';
import { Form, Icon, Input, Button, Checkbox, message, Modal } from 'antd';
import Md5 from 'js-md5';
import { connect } from 'dva'
import Style from './index.less';
import Service from '../service';
import mapopacity from "../../img/mapopacity.png"
import mapstarticon from "../../img/gjstarticpn.png"

const FormItem = Form.Item;
var map, point;
let pointArr = []
let pointMarkArr = []
let markerM, markerK;
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      uData: {},
      isSign: false,
      klongitude: 119.563277, //快递员经度
      klatitude: 29.392238,  ////快递员纬度
      mlongitude: '',
      mlatitude: '',
      rangLong: '',
      timer1: ''
    }
  }
  componentDidMount() {
    let self = this;

    let latitude = localStorage.getItem('latitude');
    let longitude = localStorage.getItem('longitude');
    let uAdressData = self.props.uAdressData;
    if (uAdressData && uAdressData.title) {
      // console.log(uAdressData.point.lng)
      pointMarkArr.push(new BMap.Point(uAdressData.point.lng, uAdressData.point.lat));
      // pointArr.push(uAdressData.point.lng,uAdressData.point.lng)
      pointArr.push({ lat: uAdressData.point.lng, log: uAdressData.point.lat });
      self.initMap(uAdressData.point.lng, uAdressData.point.lat);
      this.markerMapMy(uAdressData.point.lng, uAdressData.point.lat);
      localStorage.setItem('latitude', uAdressData.point.lat);
      localStorage.setItem('longitude', uAdressData.point.lng);

      self.getKdata();
      self.state.timer1 = setInterval(() => {
        self.getKdata('refresh');
      }, 10000)

    } else {
      // let loc = sessionStorage.getItem('loc');
      // let locStr = loc.split(',');
      // pointMarkArr.push(new BMap.Point(locStr[1], locStr[0]));
      // // pointArr.push(uAdressData.point.lng,uAdressData.point.lng)
      // pointArr.push({ lat: locStr[0], log: locStr[1] });
      // self.initMap(locStr[1], locStr[0]);
      // self.markerMapMy(locStr[1], locStr[0]);
      // localStorage.setItem('latitude', locStr[0]);
      // localStorage.setItem('longitude', locStr[1]);

      // self.getKdata();
      // self.state.timer1 = setInterval(() => {
      //   self.getKdata('refresh');
      // }, 3000)
      self.getLocation1Fun();
    }
    self.infoFun();
  }
  getLocation1Fun = (type) => {
    let self = this;
    let loc = sessionStorage.getItem('loc');
    let locStr = loc.split(',');
    let gpsPoint = new BMap.Point(locStr[1], locStr[0]);
    pointMarkArr = [];
    pointArr = [];
    setTimeout(function () {
      BMap.Convertor.translate(gpsPoint, 0, function (points) {
        let baiduPoint = points;
        pointMarkArr.push(baiduPoint);
        localStorage.setItem('latitude', points.lat);
        localStorage.setItem('longitude', points.lng);
        // pointArr.push(longitude,latitude)
        pointArr.push({ lat: points.lat, log: points.lng });
        if (!type) {
          self.initMap(points.lng, points.lat);

        }
      })
      // self.setState({
      //   mlongitude: longitude,
      //   mlatitude: latitude
      // })
      // let gpsPoint = new BMap.Point(longitude, latitude);
      // // let mk = BMap.Convertor.translate(gpsPoint, 0, translateCallback);
      // setTimeout(function () {
      //   BMap.Convertor.translate(gpsPoint, 0, function (points) {
      //     let baiduPoint = points;
      //     pointMarkArr.push(baiduPoint)
      //     // pointArr.push(longitude,latitude)
      //     pointArr.push({ lat: points.lat, log: points.lng });
      //     self.initMap(points.lng, points.lat);
      //     self.markerMapMy(points.lng, points.lat);

      //     // 快递员信息
      //     self.getKdata();
      //     self.state.timer1 = setInterval(() => {
      //       self.getKdata('refresh');
      //     }, 10000)

      //   }); //真实经纬度转成百度坐标
      // }, 2000)



      // } else {
      //   message.error('获取当前位置失败')
      // }

    })

  }
  getLocationFun = (type) => {
    let self = this;
    window.wx.getLocation({
      dataType: 'jsonp',
      type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
      success: function (res) {
        var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
        var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
        let gpsPoint = new BMap.Point(longitude, latitude);

        setTimeout(function () {
          BMap.Convertor.translate(gpsPoint, 0, function (points) {
            let baiduPoint = points;
            pointMarkArr.push(baiduPoint);
            localStorage.setItem('latitude', points.lat);
            localStorage.setItem('longitude', points.lng);
            // pointArr.push(longitude,latitude)
            pointArr.push({ lat: points.lat, log: points.lng });
            if (!type) {
              self.initMap(points.lng, points.lat);
            }
            self.markerMapMy(points.lng, points.lat);

            // 快递员信息
            self.getKdata(type);
            self.state.timer1 = setInterval(() => {
              self.getKdata('refresh');
            }, 10000)

          }); //真实经纬度转成百度坐标
        }, 2000)
      },
      fail: function () {
        console.log('失败111')
      }
    });
  }
  componentWillUnmount() {
    let self = this;
    self.props.urlStatus({
      url: '/uindex'
    });
    if (this.state.timer != null) {
      clearInterval(this.state.timer);
    }
    if (this.state.timer1 != null) {
      clearInterval(this.state.timer1);
    }

  }
  getKdata = (type) => {
    let self = this;
    const token = localStorage.getItem('token');
    let urData = self.props.urData;

    if (urData.com && urData.num) {
      self.props.queryExpress({
        params: {
          token: token,
          com: urData.com,
          num: urData.num
        },
        func: function (result) {
          if (result) {
            self.setState({
              uData: result
            })

            self.expressindexFun(result.mobile);
            // if (result) {
            //   let long = [119.563277,29.392238];
            //   message.success('快递')
            if (result.message) {
              let long = result.message.split(',');
              pointMarkArr[1] = new BMap.Point(long[0], long[1]);
              pointArr[1] = { lat: long[1], log: long[0] };
              self.markerMapK(long[0], long[1], result.realname);
              console.log('----------------')
              // 两点的距离
              self.rangingFun(pointMarkArr, type);
            } else {
              if (result.location) {
                self.getMarker(result.location, result.realname, type);
              }

            }

          }

        }
      })

    } else {
      message.error('快递信息不存在，请重新搜索快递单号进行查询!', 1.5, function () {
        self.context.router.push(`/usearchnumber`);
      });
      self.messageConfig();
    }
  }
  // 根据地址来获取经纬度
  getMarker = (adress, realname, type) => {
    let self = this;
    // let adress = self.state.detailData.address;
    // console.log(adress)
    if (!adress) {
      message.error('该地址信息有误，请联系平台管理员');
      self.messageConfig();
      return false;
    }
    local = new BMap.LocalSearch(map, {
      renderOptions: { map: map, autoViewport: true, selectFirstResult: false },
      pageCapacity: 10
    });
    map.clearOverlays();
    local.setSearchCompleteCallback(function (searchResults) {
      // console.log(searchResults);
      if (typeof (searchResults) == "undefined") {
        alert("百度API没有搜索到该地址");
        return;
      }
      if (searchResults.length > 0) {
        var searchResult = searchResults[0];
      } else {
        var searchResult = searchResults;
      }
      myIcon = new BMap.Icon("http://api.map.baidu.com/img/markers.png", new BMap.Size(23, 25), {
        offset: new BMap.Size(10, 25),
        imageOffset: new BMap.Size(0, 0 - 10 * 25)
      });

      // console.log(searchResult);

      var contents = [];
      let markerPoint = []
      map.clearOverlays();
      for (var i = 0; i < searchResult.getCurrentNumPois(); i++) {
        //获得需要得到的坐标

        // 创建标注，为要查询的地方对应的经纬度
        if (i == 0) {
          var poi = searchResult.getPoi(i);
          if (!poi) {
            alert("百度API没有搜索到该地址");
          }
          // console.log(poi);

          //设置中心点
          map.centerAndZoom(poi.point, 13);
          var marker = new BMap.Marker(new BMap.Point(poi.point.lng, poi.point.lat), { icon: myIcon });
          //alert("["+poi.point.lng+","+poi.point.lat+"]");
          //在地图上添加标识
          map.addOverlay(marker);
          // contents[i] = "你要查找的地方:【" + poi.title + "】<br/>地址：" + poi.address + "<br/>经度：" + poi.point.lng + "<br/>纬度：" + poi.point.lat;
          markerPoint.push(poi.point.lng)
          markerPoint.push(poi.point.lat);
          self.setState({ markerPoint: markerPoint })

          pointMarkArr[1] = new BMap.Point(poi.point.lat, poi.point.lng);
          pointArr[1] = { lat: poi.point.lat, log: poi.point.lng };
          self.markerMapK(poi.point.lat, poi.point.lng, realname);
          console.log(pointMarkArr);
          console.log(type);
          console.log('44444444444444')
          // 两点的距离
          self.rangingFun(pointMarkArr, type);
          // marker.setTitle(contents[i]);
        }
        //点击标识后显示的内容

        //添加点击事件监听
        // marker.addEventListener("click", makerClick);
        // if (i == 0) {
        //   var infoWindow = new BMap.InfoWindow("<p style='font-size:14px;'>" + contents[0] + "</p>");
        //   marker.openInfoWindow(infoWindow);
        // }

      }

    });
  }
  // 两个经纬度进行测距
  rangingFun = (pointMarkArr, type) => {
    // console.log(pointMarkArr)
    let self = this;
    var distance = map.getDistance(pointMarkArr[0], pointMarkArr[1]).toFixed(1);  //获取两点距离,保留小数点后两位
    console.log(distance)
    if (distance < 1000) {
      self.setState({
        rangLong: distance + "米"
      })
    } else {
      self.setState({
        rangLong: (Math.round(distance / 100) / 10).toFixed(1) + "公里"
      })
    }
    // console.log(type)
    if (!type) {
      map.setViewport(pointMarkArr);
    }

    // //门店的位置
    // var storelon = self.state.klongitude;	//门店经度
    // var storelat = self.state.klatitude;		//门店纬度
    // //当前位置
    // var curlon = self.state.mlongitude;	//当前经度	
    // var curlat = self.state.mlongitude;	//当前纬度

    // // var map = new BMap.Map("allmap");
    // var pointA = new BMap.Point(storelon, storelat);  // 创建点坐标A
    // var pointB = (new BMap.Point(curlon, curlat));  // 创建点坐标B
    // var range = map.getDistance(pointA, pointB).toFixed(2);  //获取两点距离,保留小数点后两位
    // // console.log(range)
  }
  expressindexFun = (mobile) => {
    let self = this;
    const token = localStorage.getItem('token');
    let urData = self.props.urData;
    if (urData.com && urData.num) {
      self.props.expressindex({
        params: {
          token: token,
          status: 0,
          express_mobile: mobile
        },
        func: function (result) {
          if (result && result.total_page > 0) {
            self.setState({
              isSign: true
            })

          } else {
            self.setState({
              isSign: false
            })
          }

        }
      })
    }
  }
  /* 控制提示 */
  messageConfig() {
    message.config({
      top: 100, // 消息距离顶部的位置
      duration: 2, // 默认自动关闭延时，单位秒
      maxCount: 1, // 最大显示数, 超过限制时，最早的消息会被自动关闭
    });
  }
  // 地图初始化
  initMap = (longitude, latitude) => {
    let self = this;
    map = new BMap.Map("mapWrap", { enableMapClick: false });  //创建地图
    var point = new BMap.Point(longitude, latitude);
    map.centerAndZoom(point, 7);
    map.enableScrollWheelZoom();//启动鼠标滚轮缩放地图
    map.enableKeyboard();//启动键盘操作地图
  }
  initMap1 = (pointMarkArr, pointArr) => {
    // console.log(pointArr)
    let latitude = localStorage.getItem('latitude');
    let longitude = localStorage.getItem('longitude');
    let self = this;
    map = new BMap.Map("mapWrap", { enableMapClick: false });  //创建地图
    var points = pointMarkArr;
    // var marker1 = new BMap.Marker(points[0]);   //创建7个标注  
    // var marker2 = new BMap.Marker(points[1]);   
    // map.addOverlay(marker1);                    //显示7个标注  
    // map.addOverlay(marker2);  
    let zoom = self.setZoom(pointArr);
    // console.log(zoom)

    map.centerAndZoom(points[0], zoom);                 // 初始化地图，设置中心点坐标和地图级别  
    map.addControl(new BMap.NavigationControl());      //为地图添加鱼骨  

    // var label = new BMap.Label("点击这个标注，展现7个标注的最佳视野",{position : points[0], offset: new BMap.Size(3,-6)});       //定义一个文字标签，注意1.2请用position  
    // map.addOverlay(label);  
    // point = new BMap.Point(longitude, latitude);    // 创建点坐标(默认) 这里是苏州
    // map.centerAndZoom(point, 12);                  　　   //默认缩放比例  其实打开地图的默认等级
    // //启用滚轮放大缩小 
    // ////添加控件
    // var top_left_control = new BMap.ScaleControl({ anchor: BMAP_ANCHOR_TOP_LEFT });// 左上角，添加比例尺 
    // var top_left_navigation = new BMap.NavigationControl();  //左上角，添加默认缩放平移控件
    // map.addControl(top_left_control);
    // map.addControl(top_left_navigation);
    // this.getLocation()
  }
  // 自动缩放比列
  setZoom = (points) => {
    // console.log(points)
    if (points.length > 0) {
      var maxLng = points[0].lng;
      var minLng = points[0].lng;
      var maxLat = points[0].lat;
      var minLat = points[0].lat;
      var res;
      for (var i = points.length - 1; i >= 0; i--) {
        res = points[i];
        if (res.lng > maxLng) maxLng = res.lng;
        if (res.lng < minLng) minLng = res.lng;
        if (res.lat > maxLat) maxLat = res.lat;
        if (res.lat < minLat) minLat = res.lat;
      };
      var cenLng = (parseFloat(maxLng) + parseFloat(minLng)) / 2;
      var cenLat = (parseFloat(maxLat) + parseFloat(minLat)) / 2;
      var zoom = this.getZoom(maxLng, minLng, maxLat, minLat);
      return zoom;
    } else {
      //没有坐标，显示全中国
      return 5
    }
  }
  getZoom = (maxLng, minLng, maxLat, minLat) => {
    var zoom = ["50", "100", "200", "500", "1000", "2000", "5000", "10000", "20000", "25000", "50000", "100000", "200000", "500000", "1000000", "2000000"]//级别18到3。
    var pointA = new BMap.Point(maxLng, maxLat);  // 创建点坐标A
    var pointB = new BMap.Point(minLng, minLat);  // 创建点坐标B
    var distance = map.getDistance(pointA, pointB).toFixed(1);  //获取两点距离,保留小数点后两位
    for (var i = 0, zoomLen = zoom.length; i < zoomLen; i++) {
      if (zoom[i] - distance > 0) {
        return 18 - i;//之所以会多3，是因为地图范围常常是比例尺距离的10倍以上。所以级别会增加3。
      }
    };
  }
  markerMapMy = (longitude, latitude) => {
    let self = this;
    var maker = self.addMarkerMy(new window.BMap.Point(longitude, latitude));
  }
  translateCallback = (point) => {
    let self = this;
    let baiduPoint = new BMap.Marker(point);
    let maker = self.addMarkerMy(baiduPoint);
  }
  addMarkerMy = (point) => {
    // 姓名_头像_车牌号_车架号
    const token = localStorage.getItem('token');

    // var myIcon = new BMap.Icon("http://api.map.baidu.com/img/markers.png",
    var myIcon = new BMap.Icon(mapstarticon,
      new BMap.Size(50, 50), {
        anchor: new BMap.Size(0, 0),//这句表示图片相对于所加的点的位置
        imageOffset: new BMap.Size(0, 0)

      });

    // var myIcon = new BMap.Icon("https://api.map.baidu.com/img/markers.png", new BMap.Size(23, 25), {
    //     offset: new BMap.Size(10, 25), // 指定定位位置  
    //     imageOffset: new BMap.Size(0, 0 - 12 * 25) // 设置图片偏移  
    // });
    if (markerM) {
      map.removeOverlay(markerM);
    }
    markerM = new BMap.Marker(point, { icon: myIcon });
    this.addInfoWindow(markerM, '我的位置');
    map.addOverlay(markerM);
    return markerM;
  }
  addInfoWindow = (marker, desc, type) => {
    // console.log(poi)
    // type存在的时候就显示快递员
    let self = this;
    let entity_desc = desc;
    let text;
    // let entity_desc = poi.entity_desc.split('_');
    // marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
    if (type) {
      text = '<div class="mapwrapk"><div class="mapwrap mapwrap1"><span>' + entity_desc + '</span></div><div class="mapwrapLebal"><span>快递员位置</span></div></div>';
    } else {
      text = '<div class="mapwrapLebal"><span>' + entity_desc + '</span></div>';

    }

    var label = new window.BMap.Label(text, { offset: new window.BMap.Size(20, -10) });
    marker.setLabel(label);
    var clo = "";
    var info = new window.BMap.InfoWindow("<p>" + entity_desc + "</p>"); // 创建信息窗口对象

    // map.setViewport(points);
  }

  markerMapK = (longitude, latitude, realname) => {
    let self = this;
    var maker = self.addMarkerK(new window.BMap.Point(longitude, latitude), realname);
  }
  addMarkerK = (point, realname) => {
    // console.log(point)
    // 姓名_头像_车牌号_车架号
    const token = localStorage.getItem('token');

    // var myIcon = new BMap.Icon("http://api.map.baidu.com/img/markers.png",
    var myIcon = new BMap.Icon(mapopacity,
      new BMap.Size(-38, 55), {
        // anchor: new BMap.Size(22, 51),//这句表示图片相对于所加的点的位置
        imageOffset: new BMap.Size(0, 0)

      }
    );

    // var myIcon = new BMap.Icon("https://api.map.baidu.com/img/markers.png", new BMap.Size(23, 25), {
    //     offset: new BMap.Size(10, 25), // 指定定位位置  
    //     imageOffset: new BMap.Size(0, 0 - 12 * 25) // 设置图片偏移  
    // });
    if (markerK) {
      map.removeOverlay(markerK);
    }
    markerK = new BMap.Marker(point, { icon: myIcon });
    this.addInfoWindow(markerK, realname, 'k');

    map.addOverlay(markerK);
    return markerK;
  }

  getLocation = () => {
    let self = this;
    //根据IP获取城市 
    var myCity = new BMap.LocalCity();
    // myCity.get(getCityByIP);

    // console.log(navigator.geolocation)
    //获取GPS坐标 
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        self.showMap,
        self.handleError,
        { enableHighAccuracy: true, maximumAge: 1000 }
      );
    } else {
      alert("您的浏览器不支持使用HTML 5来获取地理位置服务");
    }
  }
  handleError = () => {

  }
  showMap = (value) => {
    var longitude = value.coords.longitude;
    var latitude = value.coords.latitude;
    map = new BMap.Map("mapWrap");
    x = latitude;
    y = longitude;
    // alert("坐标经度为：" + latitude + "， 纬度为：" + longitude);
    gpsPoint = new BMap.Point(longitude, latitude); // 创建点坐标 


    //根据坐标逆解析地址 
    var geoc = new BMap.Geocoder();
    geoc.getLocation(gpsPoint, getCityByCoordinate);

    BMap.Convertor.translate(gpsPoint, 0, translateCallback);
    map.enableScrollWheelZoom(true);
  }
  editUrlFun = () => {

    this.context.router.push(`/ulocation`);
  }
  signUrlFun = () => {
    this.context.router.push(`/usign`);
  }
  // 返回
  returnFun = () => {
    this.context.router.push(`/usearchnumber`);
  }
  myUrlFun = () => {
    this.context.router.push(`/umy`);
  }
  infoFun = () => {
    Modal.info({
      title: '',
      content: (
        <div className='tcindex'>
          <p>
            您可以看到您的包裹位置以及您的收件地址，您可以详细看到包裹距离您的详细公里数。</p>

          <p> 点击【更改我的位置】，可以更改您当前的个人位置，以便查看您与包裹的距离。</p>

          <p> 如您要更改收货地址，请在包裹到达网点快递员进行可视化配送时，点击【电话】按钮，联系快递员进行地址变更。</p>

          <p> 快递员发起签收视频时，点击【前去签收】按钮，进行线上签收流程，并对配送服务进行评价。
                        </p>
        </div>
      ),
      okText: '开始查询',
      onOk() { },
    });
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    const { uData } = this.state;
    // console.log(uData)
    return (
      <div className={Style.uBoxs + ' ' + Style.wrap}>
        <div className={Style.headWrap}>
          <div className={Style.navTitle}>
            <span className={Style.arrow} onClick={this.returnFun}>
              <Icon type="left" />
            </span>
            快件派送中
            <span onClick={this.myUrlFun} className={Style.arrow + ' ' + Style.arrowText}>我的</span>
          </div>
        </div>

        <div className={Style.mapWrap} id="mapWrap">

        </div>
        <div className={Style.dataWrap}>
          <div className={Style.conWrap}>
            {uData && uData.state == 2 &&
              <span className={Style.btn + ' ' + Style.graybtn}>更改我的位置</span>
            }
            {uData && uData.state != 2 &&
              <span className={Style.btn} onClick={this.editUrlFun}>更改我的位置</span>
            }
            <p>快递员距离您：{this.state.rangLong}</p>
            <p>快递员：{uData.realname}</p>
            <p>联系方式：{uData.mobile} <span className={Style.phone}><Icon type="phone" /></span></p>
          </div>
          {this.state.isSign &&
            <div className={Style.listItem}>
              <span className={Style.btn} onClick={this.signUrlFun}>
                前去线上签收
           </span>
            </div>
          }

        </div>
      </div>
    )
  }
}

App.contextTypes = {
  router: React.PropTypes.object
}

function mapStateToProps(state, ownProps) {
  // console.log(state)
  return {
    urData: state.umodel.urData,
    uAdressData: state.umodel.uAdressData
  }
}
function dispatchToProps(dispatch) {
  return {
    saveUser(payload, params) {
      dispatch({
        type: 'login/saveUser',
        payload
      })
    },
    queryExpress(payload, params) {
      dispatch({
        type: 'umodel/queryExpress',
        payload
      })
    },
    getWechatConfig(payload, params) {
      dispatch({
        type: 'umodel/getWechatConfig',
        payload
      })
    },
    expressindex(payload, params) {
      dispatch({
        type: 'umodel/expressindex',
        payload
      })
    },
    urlStatus(payload, params) {
      dispatch({
        type: 'myHome/urlStatus',
        payload
      })
    }

  }
}
export default connect(mapStateToProps, dispatchToProps)(Form.create()(App));
